package leetcode.f1t100;

import java.util.ArrayList;
import java.util.List;

/**
 * 1到n, 所有长度为k的组合
 * https://leetcode.com/problems/combinations/
 *
 * @author lichx
 * @createTime 2023/11/27 10:19
 */
public class Q77_Combinations {

    public List<List<Integer>> combine(int n, int k) {
        int[] arr = new int[n];
        for (int i = 1; i <= n; i++) {
            arr[i - 1] = i;
        }
        List<List<Integer>> answer = new ArrayList<>();
        combine(answer, new ArrayList<Integer>(), arr, 0, n, k);
        return answer;
    }

    private void combine(List<List<Integer>> answer, List<Integer> path, int[] arr, int index, int range,
                         int length) {
        if(path.size() == length){
            answer.add(new ArrayList<>(path));
            return;
        }
        if (index == range) {
            return;
        }
        path.add(arr[index]);
        combine(answer, path, arr, index+1, range, length);
        path.remove(path.size()-1);

        combine(answer, path, arr, index+1, range, length);
    }

    public List<List<Integer>> combine_bit(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < 1 << n; i++) {
            // bit count should be k
            if (Integer.bitCount(i) == k) {
                List<Integer> comb = new ArrayList<>(k);
                for (int j = 0; j <= n; j++) {
                    // collect bit with 1
                    if (((i >> j) & 1) == 1) {
                        comb.add(j + 1);
                    }
                }
                result.add(comb);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Q77_Combinations bean = new Q77_Combinations();
        List<List<Integer>> answer = bean.combine(4, 2);
        for (List<Integer> list : answer) {
            for (Integer integer : list) {
                System.out.print(integer);
                System.out.print(" ");
            }
            System.out.println();
        }
    }
}
